package itman.elm.utils;

import java.sql.*;

public class DBUtil {

    // ThreadLocald
    private static final ThreadLocal<Connection> TL = new ThreadLocal<>();
    // URL
    private static final String URL =  "jdbc:mysql://localhost:3306/elmmall?useSSL=false&serverTimezone=UTC";
    // Driver
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    // username
    private static final String USERNAME = "root";
    // password
    private static final String PASSWORD = "1234";

    // 第一步，获取数据库连接
    public static Connection getConnection() throws SQLException {
        Connection conn = null;
        // 先去 ThreadLocal 中去获取 Connection
        // 主要目的：不浪费，实现 service 和 dao 可以共享
        conn = TL.get();
        // 然后如果发现没有，再来创建 Connection
        if (conn == null){
            conn = createConnection();
        }
        return  conn;
    }

    // 第二步，开启事务（手动开启事务）
    public static void beginTransaction() throws Exception {
        Connection conn = null;
        conn = TL.get();

        if(conn == null){
            conn = createConnection();
            TL.set(conn);
        }
        conn.setAutoCommit(false);
    }

    // 第三步，提交事务
    public static void commitTransaction() throws Exception{
        Connection conn = TL.get();
        conn.commit();
    }


    // 第四步，回滚事务
    public static void rollbackTransaction() throws Exception {
        Connection conn = TL.get();
        conn.rollback();
    }


    // 第五步，关闭资源
    public static void close(ResultSet rs, Statement stmt){
        if( rs != null){
            try{
                rs.close();
            } catch (Exception e){ e.printStackTrace(); }
        }

        if( stmt != null){
            try{
                stmt.close();
            } catch (Exception e){ e.printStackTrace();  }
        }
    }

    public static void close(Statement stmt){

        if( stmt != null){
            try{
                stmt.close();
            } catch (Exception e){ e.printStackTrace();  }
        }
    }

    public static void close(){
        Connection conn = TL.get();
        try{
            if (conn != null){
                conn.close();
            }
            TL.remove();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    // 创建 Connection
    private static Connection createConnection(){
        Connection conn = null;
        if(conn == null){
            try{
                //加载驱动
                Class.forName(DRIVER);
                //数据库连接
                conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            } catch (Exception e){
                e.printStackTrace();
            }
        }
        return conn;
    }

}
